package org.github.rayson517.easyplatform.common.web.jwt;

import javax.servlet.http.HttpServletRequest;

import org.github.rayson517.easyplatform.common.web.util.ThreadLocalUtil;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.log4j.Log4j2;

@Log4j2
public class JwtUtil {
	public static Claims getToken(HttpServletRequest request){
		String token = request.getHeader(JwtConfig.HEADER_STRING);
       
       if(token == null){
           token = request.getParameter("token");
       }
       if(log.isDebugEnabled()){
       	log.info(">>>>Token:{}", token);
       }
       
       if (token == null) 
       	throw new RuntimeException("Token解析异常, 请重新登录");
       
       ThreadLocalUtil.setValue("token", token);  // 用户id
       
       Claims claims = Jwts.parser()
               .setSigningKey(JwtConfig.SECRET)
               .parseClaimsJws(token.replace(JwtConfig.TOKEN_PREFIX, ""))
               .getBody();
       
       // parse the token.
       String userName = (String)claims.get("username");
       String userType = (String)claims.get("userType");
       String openids = (String)claims.get("openids");
       String userId = String.valueOf(claims.get("userId"));
       if(userId != null){
           ThreadLocalUtil.setValue("userId", userId);  // 用户id
           ThreadLocalUtil.setValue("companyId", String.valueOf(claims.get("companyId"))); // 公司id
           ThreadLocalUtil.setValue("userName", userName);  // 用户名
           ThreadLocalUtil.setValue("userType", userType); // 用户类型
           ThreadLocalUtil.setValue("openids", openids); // 微信openids
       }
       return claims;
	}
}
